from sqlalchemy import Column, Integer, String, ForeignKey, orm, SmallInteger
from sqlalchemy.orm import relationship, backref
from werkzeug.security import generate_password_hash, check_password_hash

from app.libs.error_code import ParameterException

from app.libs.token_auth import create_token
from app.models.base import db
from app.models.base import Base


class UserModel(Base):
    """
    用例组
    """
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    nickname = Column(String(80), unique=True, nullable=False, comment='昵称')
    username = Column(String(80), unique=True, comment='账号', nullable=False)
    auth = Column(SmallInteger, comment='权限', default=1)
    _password = Column('password', String(500))

    @orm.reconstructor
    def __init__(self):
        super(UserModel, self).__init__()
        self.fileds = ['id', 'nickname', 'username', 'auth']

    def keys(self):
        return self.fileds

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, raw):
        self._password = generate_password_hash(raw)

    @staticmethod
    def register_by_username(username, nickname, password):
        with db.auto_commit():
            user = UserModel()
            user.username = username
            user.nickname = nickname
            user.password = password
            db.session.add(user)
        # 保存至redis
        from app.libs.redis_tool.lsRedis import redisUtils
        r = redisUtils()
        r.set_key_value(username, "1")
        r.set_key_value(nickname, "1")

    def login(self, username, password):
        s = self.query.filter_by(username=username).first_or_404()
        if check_password_hash(s.password, password):
            token = create_token(s.id)
            return token
        raise ParameterException(msg='账号或者密码错误')
